<template>
  <div class="w-h-100" style="background-color: #F8F9FB;display: flex;flex-direction: column;overflow-y:auto">
    <div style="height: 46px">
      <van-nav-bar class="van"
                   title="上传视频"
                   left-arrow
                   @click-left="onClickLeft"/>
    </div>
    <div style="height: calc(100% - 46px);padding: 15px;overflow-y:auto">
      <!--          基本信息-->
      <div style="height: 39%;;border-radius:10px">

        <van-field
            required
            disabled
            v-model="userInfo.username"
            input-align="right"
            label="学生姓名"
            placeholder="请输入学生姓名"
        />
        <van-form @submit="onSubmit">
          <van-field
              required
              clearable
              input-align="right"
              v-model="userInfo.teacherName"
              label="指导老师"
              placeholder="请输入指导老师"
              :rules="[{ required: true }]"
              :show-error-message="false"
          />
        </van-form>

        <van-field
            required
            disabled
            input-align="right"
            v-model="userInfo.schoolName"
            label="所在学校"
            placeholder="请输入所在学校"
        />
        <van-field
            required
            disabled
            input-align="right"
            v-model="userInfo.gradeName"
            label="所在年级"
            placeholder="选择年级"
        />
        <van-field
            required
            disabled
            input-align="right"
            v-model="userInfo.telephone"
            label="学生电话"
            placeholder="请输入学生电话"
        />

      </div>
      <!--      分割-->
<!--      <div style="height: 2%">-->
<!--      </div>-->
      <!--          作品基本信息-->
      <div style="height: 16%;border-radius:10px">
        <van-form @submit="onSubmit">
          <van-field
              required
              v-model="userInfo.subjectName"
              input-align="right"
              label="作品类别"
              readonly
              placeholder="选择作品类别"
              :rules="[{ required: true}]"
              @click="chooseWorksClick"
              use-right-icon-slot
          >
            <van-icon slot="right-icon" name="arrow"></van-icon>
          </van-field>
          <van-field
              required
              v-model="userInfo.tutorialName"
              input-align="right"
              label="作品名称"
              clearable
              placeholder="请输入作品名称"
              :rules="[{ required: true}]"
              :show-error-message="false"
          />
        </van-form>
      </div>
      <div style="height: 1%"></div>
      <canvas ref="canvas" style="display: none;"></canvas>
      <!--上传文件-->
      <span style="color: red;margin: 0 0 0 10px">*</span><span style="font-size: 14px;margin: 0">作品内容</span>

      <div style="height: 45%;border-radius:10px;background-color: white">
        <van-form @submit="onSubmit">
          <van-field
              type="textarea "
              clearable
              v-model="userInfo.tutorialIntroduct"
              input-align="left"
              maxlength="500"
              show-word-limit
              :rules="[{ required: true}]"
              placeholder="请输入作品内容"
          />
        </van-form>

        <div v-if="showVideo">
          <van-uploader style="margin:10px 20px;border-radius: 15px" v-model="fileList"
                        :after-read="afterReadClick" :preview-image="false"
                        accept="video/mp4"
                        upload-text="上传视频"/>
          <br>
          <!--                进度条-->
          <el-progress v-if="percenFlag" :percentage="percentageValue"></el-progress>
          <span style="color: rgb(128,128,128);font-size: 12px">只能上传mp4文件，且不超过500M</span>
        </div>
        <div style="height: 160px;width: 160px;margin:10px 20px;border-radius: 15px" v-else>
          <!--           叉叉-->
          <i class="el-icon-circle-close"
             style="z-index:1;font-size: 18px;color: black;position: relative;top: 20px;left: 100%"
             @click="showVideo=true;videoOrImgShow=true"></i>
          <video controls class="w-h-100" :src="userInfo.videoUrl" v-if="videoOrImgShow"></video>
<!--          <img :src="userInfo.coverImg" class="w-h-100" v-else/>-->
          <el-image
              :src="userInfo.coverImg" fit="contain" v-else>
            <div slot="placeholder">
              加载中
              <i class="el-icon-loading"></i>
            </div>
          </el-image>
          <el-button size="mini" icon="el-icon-picture" round type="info" plain @click="updateCover">更换封面
          </el-button>
          <input type="file" style="display: none" id="file" ref="uploadVideo"
                 @change="uploadCoverClick($event)"/>
        </div>
      </div>

<!--      <div style="height: 3%"></div>-->
      <van-button type="info" round size="large"  native-type="submit" @click="onSubmit">确认上传
      </van-button>
      <div style="height: 3%"></div>
    </div>
    <van-popup
        round
        v-model="showWorksType"
        position="bottom"
        :style="{ height: '40%' }"
    >
      <div style="margin: 20px">
        <div v-for="(item,index) in worksOptions" :key="index">
          <div style="color: black;font-weight: bold;margin: 10px 0">{{ item.label }}</div>
          <el-button plain v-model="userInfo.categoryId" type="primary" round size="mini" style="margin: 5px 5px"
                     @click="chooseWorkObj(item,itemChildren)"
                     v-for="itemChildren  in item.children" :key="itemChildren.value">{{ itemChildren.label }}
          </el-button>
        </div>
      </div>
    </van-popup>


  </div>
</template>

<script>


import {getStudentInfo, getUpToken, uploadCover, uploadStudentCover} from "@/api/request";
import {worksOptions} from "@/utils/dicc";
import {loading, meassageError, meassageSuccess, meassageWarning} from "@/utils";
import {Notify} from "vant";
import {dataURLtoFile} from "@/utils/hook";

export default {
  name: 'index',
  data() {
    return {
      percentageValue: 0,//进度条数值
      percenFlag: false,
      addOrUpdateFlag: true,
      videoOrImgShow: true,
      showVideo: true,
      fileList: [],
      worksOptions,
      showWorksType: false,
      userInfo: {
        //作品id
        worksId:'',
        fileVideo: '',
        fileName: '',
        username: "",
        realname: "",
        studentLd: null,
        studentNo: "",
        telephone: "",
        sex: null,
        regionProvinceCode: "",
        regionProvinceName: "",
        regionCityCode: '',
        regionCityName: "",
        regionDistrictId: '',
        regionDistrictName: "",
        schoolName: "",
        gradeId: "",
        gradeName: "",
        classesId: null,
        classesName: null,
        classesId2: null,
        classesName2: null,
        teacherId: null,
        teacherName: "",
        parentName: null,
        //学生考试报名号
        examStudentId: '',
        //竞赛ID
        examId: '',
        //竞赛名称
        examName: '',
        //作品名称
        tutorialName: '',
        //阶段ID
        stageDetailId: '',
        //一级视频分类Id
        categoryId: '',
        //一级视频分类名称
        categoryName: '',
        //二级视频分类Id
        subjectId: '',
        //二级视频分类名称
        subjectName: '',
        //视频内容
        tutorialIntroduct: '',
        //视频链接
        videoUrl: '',
        //学生视频id，用于修改功能使用，传递该参数表明本次为修改操作
        id: '',
        //封面URL
        coverImg: '',
      },

    };
  },
  methods: {
    //提交校验
    onSubmit(value) {
      const worksObj = {
        id: this.addOrUpdateFlag ? '' : this.userInfo.worksId,	             //非必传，不传时为""
        tutorialName: this.userInfo.tutorialName,
        tutorialIntroduct: this.userInfo.tutorialIntroduct,
        videoUrl: this.userInfo.videoUrl,
        categoryId: this.userInfo.categoryId,
        categoryName: this.userInfo.categoryName,
        subjectId: this.userInfo.subjectId,
        subjectName: this.userInfo.subjectName,
        coverImg: this.userInfo.coverImg,
        teacherName: this.userInfo.teacherName
      }
      uploadStudentCover(worksObj).then(res => {
            if (res.code === 200) {
              Notify({type: "success", message: res.msg})
              this.$router.push("/videoMineH5")
            } else {
              Notify({type: "danger", message: res.msg})
            }
          },
      )
    },
    chooseWorkObj(item, itemChildren) {
      this.userInfo.categoryId = item.value
      this.userInfo.categoryName = item.label
      this.userInfo.subjectId = itemChildren.value
      this.userInfo.subjectName = itemChildren.label
      this.showWorksType = false
    },
    chooseWorksClick() {
      this.showWorksType = true
    },
    //上传封面
    uploadCoverClick() {
      const fileDom = document.getElementById("file"); // js 获取文件对象
      const fileObj = fileDom.files
      let file = fileObj[0];
      const formData = new FormData()
      formData.append('file', file) // 传入bpmn文件
      uploadCover(formData).then(res => {
        if (res.code === 200) {
          this.userInfo.coverImg = res.dataMap.url
          meassageSuccess(res.msg)
          this.videoOrImgShow = false//显示封面
        } else {
          meassageError(res.msg)
        }
      })
    },
    //更换封面
    updateCover() {
      //触发上传文件事件
      this.$refs.uploadVideo.click()

    },
    //获取读取的文件
    afterReadClick(fileObj, name) {
      if (fileObj.file) {
        //存储文件名称
        if (fileObj.file.size > 1024 * 1024 * 512) { // 500 in bytes
          return meassageWarning('文件大小不能超过500M');
        }
        if (fileObj.file.type !== 'video/mp4') { // Check if the file is MP4
          return meassageWarning('请上传MP4格式的文件');
        }

        if (fileObj.file.name.includes(".mp4")) {
          this.userInfo.fileName = fileObj.file.name//获取保存文件名称
        } else {
          this.userInfo.fileName = fileObj.file.name + ".mp4"//获取保存文件名称
        }
        const that = this
        this.percenFlag = true//打开进度条
        //七牛云配置项②
        const observer = {
          next(res) {
            // 用于展示上传进度
            console.log("七牛运next", res)
            //计算进度条数值
            that.percentageValue = parseInt(res.total.percent)
          },
          error(err) {
            meassageError("上传失败")
            console.log("七牛运next", err)
          },

          complete(res) {
            that.percenFlag = false;//上传完成，关闭进度条
            that.percentageValue=0//恢复默认值
            that.showVideo = false
            console.log("七牛云complete", res)
            Notify({type: 'success', message: '上传成功'});
            that.userInfo.videoUrl = "https://file.sycup.top/" + res.key////videoUrl
            that.userInfo.fileVideo = res.hash//保存hash值
          }
        }
        //七牛云配置项①
        const config = {
          useCdnDomain: true,
          region: null,    // 根据地区不同，官网有不同的配置
          concurrentRequestLimit: 1000,
        }
        //设置文件的配置③
        const putExtra = {
          fname: "",
          params: {},
          mimeType: null
        };
        const key = "vod/" + this.userInfo.id + "/" + fileObj.file.name  //上传文件加入用户id前缀
        getUpToken().then(res => {
          if (res.code === 200) {
            const token = res.data
            const observable = this.$qiniu.upload(fileObj.file, key, token, putExtra, config)
            const subscription = observable.subscribe(observer) // 上传开始
          }
        })

        //截图第一帧转成/png图片
        const video = document.createElement('video');
        const canvas = this.$refs.canvas;
        const context = canvas.getContext('2d');

        video.src = URL.createObjectURL(fileObj.file);
        video.addEventListener('loadedmetadata', () => {
          video.currentTime = 0; // 设置视频当前时间为第0秒
          video.addEventListener('seeked', () => {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            //base64转Blob
            // this.userInfo.coverImg = canvas.toDataURL('image/jpeg')
            const imgFile = dataURLtoFile(canvas.toDataURL('image/jpeg'))
            //上传封面
            const formData = new FormData()
            formData.append('file', imgFile) // 传入bpmn文件
            uploadCover(formData).then(res => {
              if (res.code === 200) {
                this.userInfo.coverImg = res.dataMap.url
                // meassageSuccess(res.msg)
              } else {
                meassageError(res.msg)
              }
            })
          });
        })
      }
    },
    //返回我的作品列表
    onClickLeft() {
      this.$router.push("/videoMineH5")
    }
  },
  mounted() {
//获取学生基本信息
    getStudentInfo().then(async res => {
      if (res.code === 200) {
        //对象属性拷贝
        Object.assign(this.userInfo, res.data)
        if (this.$route.query.works) {
          if (this.$route.query.works.videoInstructor) {
            this.userInfo.teacherName = this.$route.query.works.videoInstructor
          }
        }
        this.userInfo.classesId = res.data.classesName2//班级名称
      }
    })
    if (this.$route.query.works) {
      this.showVideo=false//显示视频
      const row = this.$route.query.works
      this.userInfo.teacherName = row.videoInstructor//指导老师名称
      this.userInfo.tutorialName = row.tutorialName//作品名称
      this.userInfo.categoryId = row.categoryId
      this.userInfo.subjectId = row.subjectId
      this.userInfo.categoryId = row.categoryId
      this.userInfo.categoryName = row.categoryName
      this.userInfo.subjectId = row.subjectId
      this.userInfo.subjectName = row.subjectName
      this.userInfo.tutorialIntroduct = row.tutorialIntroduct//作品内容
      this.userInfo.coverImg = row.coverImg//作品封面
      this.userInfo.fileName = row.tutorialName//视频名称
      this.userInfo.fileVideo = row.tutorialName//视频文件
      this.userInfo.videoUrl = row.videoUrl//视频文件
      this.userInfo.worksId = row.id//作品id
      this.addOrUpdateFlag = false//修改
    }

  }
}
</script>

<style scoped>
/deep/ .van-uploader__upload {
  border-radius: 10px;
}
</style>
